import { getCurrentUserId } from '@/utils/backend/auth'
import { prisma } from '@/utils/backend/db'
import { HttpStatus } from '@/utils/httpStatus'
import { NextResponse } from 'next/server'

export async function GET(req: Request, { params }: { params: { id: string } }) {
	try {
		const token = req.headers.get('Authorization')?.replace('Bearer ', '')!
		const currentUserId = await getCurrentUserId(token)
		const chatId = Number(params.id)

		// 验证用户是否有权限访问这个聊天
		const chat = await prisma.privateChat.findFirst({
			where: {
				id: chatId,
				OR: [{ user1Id: currentUserId }, { user2Id: currentUserId }],
			},
		})

		if (!chat) {
			return NextResponse.json(
				{
					success: false,
					message: '没有权限访问此聊天',
				},
				{ status: HttpStatus.FORBIDDEN }
			)
		}

		// 获取消息列表
		const messages = await prisma.privateMessage.findMany({
			where: {
				chatId,
			},
			include: {
				sender: {
					select: {
						id: true,
						username: true,
						nickname: true,
						avatar: true,
					},
				},
			},
			orderBy: {
				createdAt: 'asc',
			},
		})

		return NextResponse.json({
			success: true,
			data: messages,
		})
	} catch (error) {
		console.error('Get messages failed:', error)
		return NextResponse.json(
			{
				success: false,
				message: '获取消息列表失败',
			},
			{ status: HttpStatus.INTERNAL_SERVER_ERROR }
		)
	}
}

// 发送消息
export async function POST(req: Request, { params }: { params: { id: string } }) {
	try {
		const token = req.headers.get('Authorization')?.replace('Bearer ', '')!
		const currentUserId = await getCurrentUserId(token)
		const chatId = Number(params.id)
		const { content, type = 'text' } = await req.json()

		// 使用事务来确保数据一致性
		const result = await prisma.$transaction(async (tx) => {
			// 创建新消息
			const message = await tx.privateMessage.create({
				data: {
					content,
					type,
					status: 'sent',
					chatId,
					senderId: currentUserId,
				},
				include: {
					sender: {
						select: {
							id: true,
							username: true,
							nickname: true,
							avatar: true,
						},
					},
				},
			})

			// 更新聊天的最后一条消息
			await tx.privateChat.update({
				where: { id: chatId },
				data: {
					lastMessage: content,
					updatedAt: new Date(),
				},
			})

			return message
		})

		return NextResponse.json({
			success: true,
			data: result,
		})
	} catch (error) {
		console.error('Send message failed:', error)
		return NextResponse.json(
			{
				success: false,
				message: '发送消息失败',
			},
			{ status: HttpStatus.INTERNAL_SERVER_ERROR }
		)
	}
}
